package myExample;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JTree;
import javax.swing.LayoutStyle;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Highlighter;
import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeNode;

public class ExampleFrm extends javax.swing.JFrame {
	private static final long serialVersionUID = 1L;
	private JPanel panel;
	private JTextPane txtContent;
	private JTree treeResult;
	private JButton btnProcess;
	private JScrollPane scrollContent;
	private JScrollPane scrollResult;
	
	private Highlighter mHighLighter;
	private CPMProvider mCPMProvider;
	
	/**
	* Auto-generated main method to display this JFrame
	*/
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				ExampleFrm inst = new ExampleFrm();
				inst.setLocationRelativeTo(null);
				inst.setVisible(true);
			}
		});
	}
	
	public ExampleFrm() {
		super();
		initGUI();
		DefaultTreeModel defaultTree = (DefaultTreeModel) treeResult.getModel();
		defaultTree.setRoot(null);
		mHighLighter = txtContent.getHighlighter();				
		mCPMProvider = new CPMProvider("desc/FilesCollectionReader.xml", "desc/TownAnnotator.xml", "desc/WriterCasConsumer.xml");
	}
	
	private void initGUI() {
		try {
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			this.setTitle("UIMA");
			{
				panel = new JPanel();
				GroupLayout panelLayout = new GroupLayout((JComponent)panel);
				getContentPane().add(panel, BorderLayout.CENTER);
				panel.setLayout(panelLayout);
				panel.setPreferredSize(new java.awt.Dimension(740, 437));
				{
					btnProcess = new JButton();
					btnProcess.setText("Process");
					btnProcess.addMouseListener(new MouseAdapter() {
						public void mouseClicked(MouseEvent evt) {
							btnProcessMouseClicked(evt);
						}
					});
				}
				{
					scrollContent = new JScrollPane();
					{
						txtContent = new JTextPane();
						scrollContent.setViewportView(txtContent);
						txtContent.setPreferredSize(new java.awt.Dimension(347, 438));
					}
				}
				{
					scrollResult = new JScrollPane();
					{
						treeResult = new JTree();
						scrollResult.setViewportView(treeResult);					
						treeResult.addTreeSelectionListener(new TreeSelectionListener() {
							public void valueChanged(TreeSelectionEvent evt) {
								treeResultValueChanged(evt);
							}
						});
					}
				}
				panelLayout.setHorizontalGroup(panelLayout.createSequentialGroup()
					.addGroup(panelLayout.createParallelGroup()
					    .addComponent(scrollResult, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 355, GroupLayout.PREFERRED_SIZE)
					    .addGroup(GroupLayout.Alignment.LEADING, panelLayout.createSequentialGroup()
					        .addGap(0, 124, GroupLayout.PREFERRED_SIZE)
					        .addComponent(btnProcess, GroupLayout.PREFERRED_SIZE, 103, GroupLayout.PREFERRED_SIZE)
					        .addGap(128)))
					.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
					.addComponent(scrollContent, GroupLayout.PREFERRED_SIZE, 426, GroupLayout.PREFERRED_SIZE));
				panelLayout.setVerticalGroup(panelLayout.createSequentialGroup()
					.addGap(7)
					.addGroup(panelLayout.createParallelGroup()
					    .addGroup(GroupLayout.Alignment.LEADING, panelLayout.createSequentialGroup()
					        .addComponent(scrollResult, 0, 489, Short.MAX_VALUE)
					        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
					        .addComponent(btnProcess, GroupLayout.PREFERRED_SIZE, 28, GroupLayout.PREFERRED_SIZE)
					        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED))
					    .addComponent(scrollContent, GroupLayout.Alignment.LEADING, 0, 529, Short.MAX_VALUE))
					.addGap(6));
			}
			this.addMouseListener(new MouseAdapter() {
				public void mouseClicked(MouseEvent evt) {
				}
			});
			pack();
			this.setSize(803, 578);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void btnProcessMouseClicked(MouseEvent evt) {
		mCPMProvider = new CPMProvider("desc/FilesCollectionReader.xml", "desc/TownAnnotator.xml", "desc/WriterCasConsumer.xml");
		mCPMProvider.Process();		
		JOptionPane.showMessageDialog(this, "Completed!!!");
		loadTreeResult();
	}
	
	String preParent;
	private void treeResultValueChanged(TreeSelectionEvent evt) {		
		//TODO add your code for treeResult.valueChanged
		MutableTreeNode node = (MutableTreeNode) evt.getPath().getLastPathComponent();	
		if (node.toString().compareTo("Files") == 0)
			return;
		TreeNode parent = node.getParent();
		boolean isFile = false;
		String file = parent.toString();
		if (parent.toString().compareTo("Files") == 0) {
			file = node.toString();
			isFile = true;
		}
		if (preParent != file) {
			// load content...
			FileInputStream input;
			try {
				input = new FileInputStream("../MyExample/output/" + file);
				BufferedReader reader = new BufferedReader(new InputStreamReader(input,"UTF-8"));
				String line;
				StringBuilder str = new StringBuilder();
				while ((line = reader.readLine()) != null) {
					str.append(line);
				}
				reader.close();
				txtContent.setText(str.toString());			
			} catch (Exception e) {			
			}
		}
		if (!isFile) {
			// highlight text
			String[] value = node.toString().trim().split("\b");
			int begin = Integer.parseInt(value[1]);
			int end = Integer.parseInt(value[2]);
			try {
				txtContent.setCaretPosition(begin);
				mHighLighter.addHighlight(begin, end, new DefaultHighlightPainter(Color.LIGHT_GRAY));				
			} catch (BadLocationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
				
	}
	
	private void loadTreeResult() {
		DefaultTreeModel defaultTree = (DefaultTreeModel) treeResult.getModel();
		DefaultMutableTreeNode root = new DefaultMutableTreeNode("Files");		
		defaultTree.setRoot(root);		
		FileInputStream input;
		try {
			// read result
			input = new FileInputStream("../MyExample/output/result.txt");
			BufferedReader reader = new BufferedReader(new InputStreamReader(input,"UTF-8"));
			String line;
			DefaultMutableTreeNode fileNode = null;
			while ((line = reader.readLine()) != null) {
				if (line.substring(0, 1).compareTo("\t") != 0) {
					fileNode = new DefaultMutableTreeNode(line);
			        root.add(fileNode);			        
				}
				else {
					DefaultMutableTreeNode townNode = new DefaultMutableTreeNode(line.replace("\t", "\b"));		    				 
		    		fileNode.add(townNode);					
				}
			}			
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
